package br.com.imob.collector;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import br.com.imob.exception.ParserException;
import br.com.imob.model.ImobItem;
import br.com.imob.util.Goal;
import br.com.imob.util.Imob;

public class MultiParser extends GenericParser {

	private static final Logger log = Logger.getLogger(MultiParser.class);

	private String urlRent;
	private String urlPurchase;

	@Override
	public List<ImobItem> collectAllItems() throws ParserException {

		List<ImobItem> items = new ArrayList<ImobItem>();

		items = collectAllItems( Goal.RENT );

		items.addAll( collectAllItems( Goal.PURCHASE ) );

		return items;

	}

	public List<ImobItem> collectAllItems(Goal goal) throws ParserException {

		log.info("Collecting all items from Multi: " + goal.toString());

		List<ImobItem> items = new ArrayList<ImobItem>();

		try {

			String url = goal.equals(Goal.RENT) ? urlRent : urlPurchase;

			Document doc = Jsoup.connect(url).get();

			Element ulElement = doc.getElementById("listaImoveis");
			Elements liElements = ulElement.getElementsByTag("li");
			for (Element eImobs : liElements) {

				ImobItem item = new ImobItem();

				Element code = eImobs.getElementById("codigo");
				item.setCode(code != null ? code.text() : null);

				if (code != null) {
					Element neighbor = eImobs.getElementById("bairro");
					item.setNeighbor(neighbor != null ? neighbor.text() : null);

					Element price = eImobs.getElementById("valor");
					String tmp = price.text();
					int idx = tmp.indexOf(',');
					tmp = tmp.substring(3, idx);
					tmp = tmp.replaceAll("\\.", "");
					item.setPrice(price != null ? Float.parseFloat(tmp) : null);

					Element photo = eImobs.getElementById("foto");
					if (photo == null)
						item.setThumbnail(null);
					else if (photo.getElementsByTag("img").isEmpty())
						item.setThumbnail(null);
					else
						item.setThumbnail(photo.getElementsByTag("img").get(0)
								.absUrl("src"));

					Elements links = eImobs.select("a");
					if (links.size() > 0) {
						item.setLink(links.first().attr("abs:href"));
					}

					item.setImob( Imob.MULTI.toString() );

					item.setGoal( goal.toString() );
					
					item.setId( item.getCode() + "-" + item.getImob() );

					items.add(item);
				}

			}
			log.info(">> Items found: " + items.size() + " <<");

		} catch (IOException e) {
			throw new ParserException(e);
		}
		return items;

	}

	public String getUrlRent() {
		return urlRent;
	}

	public void setUrlRent(String urlRent) {
		this.urlRent = urlRent;
	}

	public String getUrlPurchase() {
		return urlPurchase;
	}

	public void setUrlPurchase(String urlPurchase) {
		this.urlPurchase = urlPurchase;
	}

}
